import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'package:signature/signature.dart';
import '../../../common/models/index.dart';

import 'index.dart';

class CaigouAssessmentDetialPage extends StatefulWidget {
  const CaigouAssessmentDetialPage({super.key});

  @override
  State<CaigouAssessmentDetialPage> createState() => _CaigouAssessmentDetialPageState();
}

class _CaigouAssessmentDetialPageState extends State<CaigouAssessmentDetialPage> {
  int _selectedIndex = 0;
  int _ruleTabIndex = 0; // 0-评分规则，1-资格评审规则，2-供应商信息，3-招标文件，4-投标文件
  bool _hasInitializedRuleTab = false; // 标记是否已初始化规则Tab
  
  // 用于管理评分标准的展开/收起状态 key: 评分项标识, value: 是否展开
  final Map<String, bool> _expandedStandards = {};

  CaigouAssessmentDetialController get controller => Get.find<CaigouAssessmentDetialController>();

  // 项目详情视图
  Widget _buildProjectDetailView() {
    return Obx(() {
      if (controller.isLoading.value) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      if (controller.errorMessage.value.isNotEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.error_outline, size: 48, color: Colors.red),
              const SizedBox(height: 16),
              Text(
                controller.errorMessage.value,
                style: const TextStyle(fontSize: 16, color: Colors.red),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: controller.refreshProjectDetail,
                child: const Text('重试'),
              ),
            ],
          ),
        );
      }
      
      if (controller.project.value == null) {
        return const Center(
          child: Text('暂无项目信息'),
        );
      }
      
      final project = controller.project.value!;
      return RefreshIndicator(
        onRefresh: controller.refreshProjectDetail,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildProjectHeader(project),
              const SizedBox(height: 8),
              _buildProjectInfo(project),
              const SizedBox(height: 8),
              _buildProjectDetails(project),
            ],
          ),
        ),
      );
    });
  }

  // 供应商列表视图
  Widget _buildSuppliersView() {
    return Obx(() {
      if (controller.isLoading.value) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      return RefreshIndicator(
        onRefresh: controller.refreshProjectSuppliers,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: _buildProjectSuppliers(),
        ),
      );
    });
  }

  // 评标专家列表视图
  Widget _buildExpertsView() {
    return Obx(() {
      if (controller.isLoading.value) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      return RefreshIndicator(
        onRefresh: controller.refreshProjectExperts,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: _buildProjectExperts(),
        ),
      );
    });
  }

  // 项目头部信息
  Widget _buildProjectHeader(ProjectModel project) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade100, width: 1),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 6,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.blue.shade50,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Icon(
                    Icons.assignment_outlined,
                    color: Colors.blue.shade600,
                    size: 20,
                  ),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: Text(
              project.projectName ?? '未知项目',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.grey[900],
                      height: 1.3,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 10),
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  decoration: BoxDecoration(
                    color: ProjectModel.getStatusColorByValue(project.status).withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: ProjectModel.getStatusColorByValue(project.status).withOpacity(0.3),
                      width: 1,
                    ),
                  ),
                  child: Text(
                    ProjectModel.getStatusTextByValue(project.status),
                    style: TextStyle(
                      color: ProjectModel.getStatusColorByValue(project.status),
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
                const Spacer(),
                if (project.budgetAmount != null && project.budgetAmount.toString() != 'null')
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                    decoration: BoxDecoration(
                      color: Colors.green.shade50,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          Icons.account_balance_wallet_rounded,
                          size: 14,
                          color: Colors.green.shade700,
                        ),
                        const SizedBox(width: 4),
                  Text(
                    '预算：${project.budgetAmount}万元',
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w600,
                            color: Colors.green.shade700,
                          ),
                        ),
                      ],
                    ),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 项目基本信息
  Widget _buildProjectInfo(ProjectModel project) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade100, width: 1),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 6,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(Icons.info_outline, color: Colors.blue.shade600, size: 16),
                const SizedBox(width: 6),
            const Text(
              '基本信息',
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
            ),
              ],
            ),
            const SizedBox(height: 10),
            _buildInfoRow('申报部门', project.declareDepartment),
            _buildInfoRow('项目编号', project.projectNo),
            _buildInfoRow('申报时间', project.declareTime),
            _buildInfoRow('项目联系人', project.projectContact),
            _buildInfoRow('联系电话', project.phone),
            _buildInfoRow('项目经理', project.projectManager),
          ],
        ),
      ),
    );
  }

  // 项目详细信息
  Widget _buildProjectDetails(ProjectModel project) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade100, width: 1),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 6,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(Icons.description_outlined, color: Colors.blue.shade600, size: 16),
                const SizedBox(width: 6),
            const Text(
              '项目详情',
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
            ),
              ],
            ),
            const SizedBox(height: 10),
            if (project.background?.isNotEmpty == true) ...[
              _buildDetailSection('项目背景', project.background!),
              const SizedBox(height: 8),
            ],
            if (project.requirements?.isNotEmpty == true) ...[
              _buildDetailSection('项目要求', project.requirements!),
              const SizedBox(height: 8),
            ],
            if (project.objectives?.isNotEmpty == true) ...[
              _buildDetailSection('项目目标', project.objectives!),
              const SizedBox(height: 8),
            ],
            if (project.reviewSuggestions?.toString().isNotEmpty == true) ...[
              _buildDetailSection('评审建议', project.reviewSuggestions.toString()),
            ],
          ],
        ),
      ),
    );
  }

  // 信息行
  Widget _buildInfoRow(String label, String? value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 3),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label：',
              style: TextStyle(
                fontWeight: FontWeight.w500,
                fontSize: 12,
                color: Colors.grey[600],
              ),
            ),
          ),
          Expanded(
            child: Text(
              value?.isNotEmpty == true ? value! : '暂无',
              style: TextStyle(
                fontSize: 12,
                color: value?.isNotEmpty == true ? Colors.grey[800] : Colors.grey[400],
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 详情节
  Widget _buildDetailSection(String title, String content) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(
              width: 3,
              height: 14,
              decoration: BoxDecoration(
                color: Colors.blue.shade600,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(width: 6),
        Text(
          title,
              style: TextStyle(
                fontWeight: FontWeight.w600,
                fontSize: 13,
                color: Colors.grey[800],
        ),
            ),
          ],
        ),
        const SizedBox(height: 6),
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: Colors.grey.shade50,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: Colors.grey.shade200, width: 1),
          ),
          child: Text(
            content,
            style: const TextStyle(fontSize: 12, height: 1.5),
          ),
        ),
      ],
    );
  }

  // 项目供应商列表
  Widget _buildProjectSuppliers() {
    return Obx(() {
      return Container(
        margin: const EdgeInsets.only(bottom: 8),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.grey.shade100, width: 1),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.03),
              blurRadius: 6,
              offset: const Offset(0, 1),
            ),
          ],
        ),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.business_outlined, color: Colors.blue.shade600, size: 16),
                  const SizedBox(width: 6),
                  const Text(
                    '供应商列表',
                    style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
                  ),
                  const Spacer(),
                  if (controller.isLoadingSuppliers.value)
                    SizedBox(
                      width: 14,
                      height: 14,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.blue.shade600),
                      ),
                    )
                  else
                    IconButton(
                      icon: Icon(Icons.refresh_rounded, size: 16, color: Colors.grey.shade600),
                      onPressed: controller.refreshProjectSuppliers,
                      tooltip: '刷新供应商列表',
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                    ),
                ],
              ),
              const SizedBox(height: 10),
              
              if (controller.supplierErrorMessage.value.isNotEmpty)
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.red.shade50,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: Colors.red.shade200),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.error_outline, color: Colors.red.shade600, size: 20),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          controller.supplierErrorMessage.value,
                          style: TextStyle(color: Colors.red.shade600, fontSize: 14),
                        ),
                      ),
                      TextButton(
                        onPressed: controller.refreshProjectSuppliers,
                        child: const Text('重试'),
                      ),
                    ],
                  ),
                )
              else               if (controller.projectSuppliers.isEmpty && !controller.isLoadingSuppliers.value)
                Container(
                  padding: const EdgeInsets.all(12),
                  child: Row(
                    children: [
                      Icon(Icons.info_outline, color: Colors.grey.shade600, size: 20),
                      const SizedBox(width: 8),
                      Text(
                        '暂无供应商信息',
                        style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
                      ),
                    ],
                  ),
                )
              else
                ListView.separated(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: controller.projectSuppliers.length,
                  separatorBuilder: (context, index) => const Divider(height: 1),
                  itemBuilder: (context, index) {
                    final supplier = controller.projectSuppliers[index];
                    return _buildSupplierItem(supplier);
                  },
                ),
            ],
          ),
        ),
      );
    });
  }

  // 构建信息项（用于供应商详细信息卡片）
  Widget _buildInfoItem({
    required IconData icon,
    required Color iconColor,
    required String label,
    required String value,
    bool isMultiLine = false,
  }) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 图标
        Container(
          padding: const EdgeInsets.all(6),
          decoration: BoxDecoration(
            color: iconColor.withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(
            icon,
            size: 16,
            color: iconColor,
          ),
        ),
        const SizedBox(width: 10),
        
        // 标签和值
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                label,
                style: TextStyle(
                  fontSize: 11,
                  color: Colors.grey.shade500,
                  fontWeight: FontWeight.w500,
                  height: 1.2,
                ),
              ),
              const SizedBox(height: 2),
              Text(
                value,
                style: TextStyle(
                  fontSize: 13,
                  color: Colors.grey.shade800,
                  fontWeight: FontWeight.w500,
                  height: 1.3,
                ),
                maxLines: isMultiLine ? 2 : 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 供应商项目
  Widget _buildSupplierItem(ProjectSupplier supplier) {
    // 构建单行信息文本
    List<String> infoItems = [];
    if (supplier.legalPerson?.isNotEmpty == true && supplier.legalPerson != 'null') {
      infoItems.add('法人：${supplier.legalPerson}');
    }
    if (supplier.contacts?.isNotEmpty == true && supplier.contacts != 'null') {
      infoItems.add('${supplier.contacts}');
    }
    if (supplier.phone?.isNotEmpty == true && supplier.phone != 'null') {
      infoItems.add('${supplier.phone}');
    }
    if (supplier.corpAddress?.isNotEmpty == true && supplier.corpAddress != 'null') {
      infoItems.add('${supplier.corpAddress}');
    }
    
    return InkWell(
      onTap: () => controller.showSupplierBidBottomSheet(supplier),
      borderRadius: BorderRadius.circular(6),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 4),
        child: Row(
          children: [
            // 供应商图标
            Container(
              width: 36,
              height: 36,
              decoration: BoxDecoration(
                color: Colors.indigo.shade50,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(
                Icons.business,
                color: Colors.indigo.shade600,
                size: 20,
              ),
            ),
            const SizedBox(width: 10),
            
            // 供应商信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 供应商名称
                  Text(
                    supplier.corpName ?? '未知供应商',
                    style: const TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w600,
                      height: 1.2,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  
                  // 单行显示所有信息
                  if (infoItems.isNotEmpty) ...[
                    const SizedBox(height: 4),
                    Text(
                      infoItems.join('  •  '),
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey.shade600,
                        height: 1.2,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ],
              ),
            ),
            
            const SizedBox(width: 8),
            
            // 评标状态标签（更紧凑）
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
              decoration: BoxDecoration(
                color: supplier.bidFlag == 1 
                    ? Colors.green.shade50 
                    : Colors.orange.shade50,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: supplier.bidFlag == 1 
                      ? Colors.green.shade300 
                      : Colors.orange.shade300,
                  width: 1,
                ),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: 6,
                    height: 6,
                    decoration: BoxDecoration(
                      color: supplier.bidFlag == 1 
                          ? Colors.green.shade600 
                          : Colors.orange.shade600,
                      shape: BoxShape.circle,
                    ),
                  ),
                  const SizedBox(width: 4),
                  Text(
                    supplier.bidFlag == 1 ? '已评标' : '待评标',
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: supplier.bidFlag == 1 
                          ? Colors.green.shade700 
                          : Colors.orange.shade700,
                      height: 1,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }


  // 供应商评标底部弹窗
  Widget _buildSupplierBidBottomSheet() {
    return Obx(() {
      if (!controller.showSupplierBidSheet.value) {
        // 弹窗关闭时，重置所有状态
        _hasInitializedRuleTab = false;
        _expandedStandards.clear();
        return const SizedBox.shrink();
      }

      final supplier = controller.selectedSupplier.value;
      if (supplier == null) {
        return const SizedBox.shrink();
      }

      // 只在首次打开弹窗时重置规则Tab索引为0（评分规则）
      if (!_hasInitializedRuleTab) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            setState(() {
              _ruleTabIndex = 0;
              _hasInitializedRuleTab = true;
            });
          }
        });
      }

      return GestureDetector(
        onTap: controller.hideSupplierBidBottomSheet,
        child: Container(
          color: Colors.black.withOpacity(0.5),
          child: GestureDetector(
            onTap: () {}, // 阻止事件冒泡
            child: DraggableScrollableSheet(
              initialChildSize: 0.85,
              minChildSize: 0.5,
              maxChildSize: 0.95,
              builder: (context, scrollController) {
                return Container(
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
                  ),
                  child: Column(
                    children: [
                      // 拖拽指示器
                      Container(
                        margin: const EdgeInsets.symmetric(vertical: 8),
                        width: 40,
                        height: 4,
                        decoration: BoxDecoration(
                          color: Colors.grey.shade300,
                          borderRadius: BorderRadius.circular(2),
                        ),
                      ),
                      
                      // 供应商信息标题栏（白色主题优化版）
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border(
                            bottom: BorderSide(color: Colors.grey.shade100, width: 1),
                          ),
                        ),
                        child: Row(
                          children: [
                            // 供应商图标
                            Container(
                              width: 48,
                              height: 48,
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [Colors.blue.shade400, Colors.blue.shade600],
                                  begin: Alignment.topLeft,
                                  end: Alignment.bottomRight,
                                ),
                                borderRadius: BorderRadius.circular(12),
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.blue.withOpacity(0.2),
                                    blurRadius: 8,
                                    offset: const Offset(0, 2),
                                  ),
                                ],
                              ),
                              child: const Icon(
                                Icons.business_rounded,
                                color: Colors.white,
                                size: 24,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    supplier.corpName ?? '未知供应商',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.grey.shade900,
                                      height: 1.2,
                                    ),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  if (supplier.legalPerson?.isNotEmpty == true && 
                                      supplier.legalPerson != 'null') ...[
                                    const SizedBox(height: 4),
                                    Row(
                                      children: [
                                        Icon(
                                          Icons.person_outline_rounded,
                                          size: 14,
                                          color: Colors.grey.shade500,
                                        ),
                                        const SizedBox(width: 4),
                                        Flexible(
                                          child: Text(
                                      '法人：${supplier.legalPerson}',
                                      style: TextStyle(
                                              fontSize: 12,
                                              color: Colors.grey.shade600,
                                              height: 1.2,
                                      ),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ],
                              ),
                            ),
                            const SizedBox(width: 8),
                            // 关闭按钮
                            InkWell(
                              onTap: controller.hideSupplierBidBottomSheet,
                              borderRadius: BorderRadius.circular(20),
                              child: Container(
                                padding: const EdgeInsets.all(6),
                        decoration: BoxDecoration(
                                  color: Colors.grey.shade100,
                                  borderRadius: BorderRadius.circular(20),
                                ),
                                child: Icon(
                                  Icons.close_rounded,
                                  size: 18,
                                  color: Colors.grey.shade600,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      
                      // 内容区域
                      Expanded(
                        child: _buildRulesContent(scrollController),
                      ),
                      
                      // 底部操作区域
                      _buildBottomActionBar(),
                    ],
                  ),
                );
              },
            ),
          ),
        ),
      );
    });
  }

  // 底部操作区域 - 两步提交流程
  Widget _buildBottomActionBar() {
    return Obx(() {
      final scoreSubmitted = controller.scoreSubmitted.value;
      
      return Container(
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            top: BorderSide(color: Colors.grey.shade300, width: 1),
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 4,
              offset: const Offset(0, -2),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 流程指示器
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                border: Border(
                  bottom: BorderSide(color: Colors.blue.shade100),
                ),
              ),
              child: Row(
                children: [
                  // 第一步
                  Expanded(
                    child: Row(
                      children: [
                        Container(
                          width: 24,
                          height: 24,
                          decoration: BoxDecoration(
                            color: scoreSubmitted ? Colors.green : Colors.blue.shade600,
                            shape: BoxShape.circle,
                          ),
                          child: Center(
                            child: scoreSubmitted
                                ? const Icon(Icons.check, size: 16, color: Colors.white)
                                : const Text('1', style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.bold)),
                          ),
                        ),
                        const SizedBox(width: 6),
                        Flexible(
                          child: Text(
                            scoreSubmitted ? '评分已提交' : '评分+组长',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                              color: scoreSubmitted ? Colors.green : Colors.blue.shade700,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  
                  // 箭头
                  Icon(Icons.arrow_forward, size: 16, color: Colors.grey.shade400),
                  const SizedBox(width: 8),
                  
                  // 第二步
                  Expanded(
                    child: Row(
                      children: [
                        Container(
                          width: 24,
                          height: 24,
                          decoration: BoxDecoration(
                            color: scoreSubmitted ? Colors.blue.shade600 : Colors.grey.shade300,
                            shape: BoxShape.circle,
                          ),
                          child: Center(
                            child: Text(
                              '2',
                              style: TextStyle(
                                color: scoreSubmitted ? Colors.white : Colors.grey.shade500,
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 6),
                        Flexible(
                          child: Text(
                            '签名提交',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                              color: scoreSubmitted ? Colors.blue.shade700 : Colors.grey.shade500,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            
            // 根据当前步骤显示不同的按钮
            if (!scoreSubmitted) ...[
              // 第一步：组长选择 + 提交评分按钮
              Container(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    // 组长选择（第一步）
                    Obx(() {
                      final isSelected = controller.isTeamLeader.value;
                      final isChecking = controller.isCheckingLastExpert.value;
                      
                      return InkWell(
                        onTap: isChecking ? null : controller.onLeaderCheckboxTap,
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(color: Colors.grey.shade300),
                            color: isChecking 
                                ? Colors.grey.shade100
                                : isSelected 
                                    ? Colors.blue.shade50 
                                    : Colors.grey.shade50,
                          ),
                          child: Row(
                            children: [
                              // 如果正在检查，显示加载指示器
                              if (isChecking)
                                SizedBox(
                                  width: 20,
                                  height: 20,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2.5,
                                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue.shade600),
                                  ),
                                )
                              else
                                Icon(
                                  isSelected ? Icons.check_box : Icons.check_box_outline_blank,
                                  color: isSelected ? Colors.blue.shade600 : Colors.grey.shade600,
                                  size: 20,
                                ),
                              const SizedBox(width: 8),
                              Expanded(
                                child: Text(
                                  isChecking ? '正在验证组长资格...' : '我是组长',
                                  style: TextStyle(
                                    fontSize: 14,
                                    fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                                    color: isChecking
                                        ? Colors.grey.shade600
                                        : isSelected 
                                            ? Colors.blue.shade800 
                                            : Colors.black87,
                                  ),
                                ),
                              ),
                              if (!isChecking) ...[
                                Icon(
                                  Icons.info_outline,
                                  size: 16,
                                  color: Colors.grey.shade600,
                                ),
                                const SizedBox(width: 4),
                                Text(
                                  '组长需填写评标总意见',
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Colors.grey.shade600,
                                  ),
                                ),
                              ],
                            ],
                          ),
                        ),
                      );
                    }),
                    const SizedBox(height: 12),
                    
                    // 提交评分按钮
                    SizedBox(
                      width: double.infinity,
                      height: 48,
                      child: ElevatedButton.icon(
                        onPressed: controller.submitScoreTable,
                        icon: const Icon(Icons.check_circle_outline, size: 20),
                        label: const Text(
                          '提交评分',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue.shade600,
                          foregroundColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          elevation: 2,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ] else ...[
              // 第二步：签名和意见区域
              Container(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    // 组长意见输入框（仅组长可见）
                    if (controller.isTeamLeader.value) ...[
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.blue.shade50,
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(color: Colors.blue.shade200),
                        ),
                        child: TextField(
                          maxLines: 3,
                          onChanged: controller.updateBidOpinion,
                          decoration: InputDecoration(
                            hintText: '请输入评标总意见（组长必填）...',
                            hintStyle: TextStyle(
                              fontSize: 12,
                              color: Colors.grey.shade400,
                            ),
                            border: InputBorder.none,
                            contentPadding: const EdgeInsets.all(12),
                            prefixIcon: Icon(Icons.edit_note, size: 20, color: Colors.blue.shade600),
                            labelText: '评标总意见',
                            labelStyle: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: Colors.blue.shade700,
                            ),
                            floatingLabelBehavior: FloatingLabelBehavior.always,
                          ),
                          style: const TextStyle(fontSize: 13),
                        ),
                      ),
                      const SizedBox(height: 12),
                    ],
                    
                    // 提交签名按钮（全宽）
                    SizedBox(
                      width: double.infinity,
                      height: 48,
                      child: ElevatedButton.icon(
                        onPressed: controller.isUploading.value ? null : controller.uploadSignatureAndOpinion,
                        icon: controller.isUploading.value
                            ? const SizedBox(
                                width: 20,
                                height: 20,
                                child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                              )
                            : const Icon(Icons.upload, size: 20),
                        label: Text(
                          controller.isUploading.value ? '提交中...' : '提交签名',
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.green.shade600,
                          foregroundColor: Colors.white,
                          disabledBackgroundColor: Colors.grey.shade400,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          elevation: 2,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ],
        ),
      );
    });
  }

  // 规则内容区域
  Widget _buildRulesContent(ScrollController scrollController) {
    return Obx(() {
      final scoreSubmitted = controller.scoreSubmitted.value;
      
      if (controller.isLoadingRules.value) {
        return const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('正在加载评审规则...'),
            ],
          ),
        );
      }

      if (controller.ruleErrorMessage.value.isNotEmpty) {
        return Center(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.error_outline, size: 48, color: Colors.red),
                const SizedBox(height: 16),
                Text(
                  controller.ruleErrorMessage.value,
                  style: const TextStyle(fontSize: 16, color: Colors.red),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: controller.refreshProjectReviewRules,
                  child: const Text('重试'),
                ),
              ],
            ),
          ),
        );
      }

      final rules = controller.projectRules.value;
      if (rules == null) {
        return const Center(
          child: Text('暂无评审规则信息'),
        );
      }

      return Column(
        children: [
          // 第一步：评分规则、资格评审规则、供应商信息、投标文件（使用Tab切换）
          if (!scoreSubmitted) ...[
            // 规则Tab切换器
            _buildRuleTabSwitcher(),
            
            // 规则内容区域
            Expanded(
              child: _ruleTabIndex == 0
                  ? SingleChildScrollView(
        controller: scrollController,
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                      child: _buildScoreRulesContent(rules),
                    )
                  : _ruleTabIndex == 1
                      ? SingleChildScrollView(
                          controller: scrollController,
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                          child: _buildReviewRulesContent(rules),
                        )
                      : _ruleTabIndex == 2
                          ? _buildSupplierInfoContent()
                          : _ruleTabIndex == 3
                              ? _buildBidFilesContent()
                              : _buildSupplierFilesContent(),
            ),
          ]
          // 第二步：显示签名板
          else ...[
            Expanded(
              child: SingleChildScrollView(
                controller: scrollController,
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                child: _buildSignatureSection(),
              ),
            ),
          ],
        ],
      );
    });
  }
  
  // 规则Tab切换器（更紧凑，分两行显示）
  Widget _buildRuleTabSwitcher() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      padding: const EdgeInsets.all(3),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: Colors.grey.shade200, width: 1),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.02),
            blurRadius: 4,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Column(
        children: [
          // 第一行：评分规则、资格评审、供应商
          Row(
            children: [
              Expanded(
                child: _buildRuleTabButton(
                  index: 0,
                  icon: Icons.score_outlined,
                  label: '评分规则',
                ),
              ),
              const SizedBox(width: 3),
              Expanded(
                child: _buildRuleTabButton(
                  index: 1,
                  icon: Icons.checklist_outlined,
                  label: '资格评审',
                ),
              ),
              const SizedBox(width: 3),
              Expanded(
                child: _buildRuleTabButton(
                  index: 2,
                  icon: Icons.business_outlined,
                  label: '供应商',
                ),
              ),
            ],
          ),
          const SizedBox(height: 3),
          // 第二行：招标文件、投标文件
          Row(
            children: [
              Expanded(
                child: _buildRuleTabButton(
                  index: 3,
                  icon: Icons.description_outlined,
                  label: '招标文件',
                ),
              ),
              const SizedBox(width: 3),
              Expanded(
                child: _buildRuleTabButton(
                  index: 4,
                  icon: Icons.attach_file_outlined,
                  label: '投标文件',
                ),
              ),
              // 占位，保持对齐
              const Expanded(child: SizedBox()),
            ],
          ),
        ],
      ),
    );
  }
  
  // 规则Tab按钮
  Widget _buildRuleTabButton({
    required int index,
    required IconData icon,
    required String label,
  }) {
    final isSelected = _ruleTabIndex == index;
    
    return GestureDetector(
      onTap: () {
        setState(() {
          _ruleTabIndex = index;
        });
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.symmetric(vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? Colors.blue.shade600 : Colors.transparent,
          borderRadius: BorderRadius.circular(7),
          boxShadow: isSelected
              ? [
                  BoxShadow(
                    color: Colors.blue.withOpacity(0.25),
                    blurRadius: 3,
                    offset: const Offset(0, 2),
                  ),
                ]
              : null,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              icon,
              size: 16,
              color: isSelected ? Colors.white : Colors.grey.shade600,
            ),
            const SizedBox(width: 4),
            Text(
              label,
              style: TextStyle(
                fontSize: 12,
                fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
                color: isSelected ? Colors.white : Colors.grey.shade600,
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  // 评分规则内容
  Widget _buildScoreRulesContent(rules) {
    if (rules.scoreRule?.isNotEmpty == true) {
      return _buildScoreRulesSection(rules.scoreRule!);
    } else {
      return const Center(
                  child: Padding(
                    padding: EdgeInsets.all(24),
                    child: Text(
            '暂无评分规则配置',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey,
                      ),
                    ),
                  ),
      );
    }
  }
  
  // 资格评审规则内容
  Widget _buildReviewRulesContent(rules) {
    if (rules.reviewRule?.isNotEmpty == true) {
      return _buildReviewRulesSection(rules.reviewRule!);
    } else {
      return const Center(
        child: Padding(
          padding: EdgeInsets.all(24),
          child: Text(
            '暂无资格评审规则配置',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
        ),
      );
    }
  }
  
  // 供应商信息内容（只显示基本信息）
  Widget _buildSupplierInfoContent() {
    final supplier = controller.selectedSupplier.value;
    if (supplier == null) {
      return const Center(
        child: Padding(
          padding: EdgeInsets.all(24),
          child: Text(
            '暂无供应商信息',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
        ),
      );
    }
    
    return SingleChildScrollView(
      padding: const EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 供应商基本信息卡片
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.grey.shade200, width: 1),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.02),
                  blurRadius: 4,
                  offset: const Offset(0, 1),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题
                Row(
                  children: [
                    Icon(Icons.info_outline, color: Colors.blue.shade600, size: 18),
                    const SizedBox(width: 8),
                    const Text(
                      '基本信息',
                      style: TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                
                // 联系人
                if (supplier.contacts?.isNotEmpty == true && supplier.contacts != 'null')
                  _buildInfoItem(
                    icon: Icons.person_outline_rounded,
                    iconColor: Colors.blue.shade600,
                    label: '联系人',
                    value: supplier.contacts!,
                  ),
                
                // 联系电话
                if (supplier.phone?.isNotEmpty == true && supplier.phone != 'null') ...[
                  if (supplier.contacts?.isNotEmpty == true && supplier.contacts != 'null')
                    const SizedBox(height: 12),
                  _buildInfoItem(
                    icon: Icons.phone_outlined,
                    iconColor: Colors.green.shade600,
                    label: '电话',
                    value: supplier.phone!,
                  ),
                ],
                
                // 企业地址
                if (supplier.corpAddress?.isNotEmpty == true && supplier.corpAddress != 'null') ...[
                  if ((supplier.contacts?.isNotEmpty == true && supplier.contacts != 'null') || 
                      (supplier.phone?.isNotEmpty == true && supplier.phone != 'null'))
                    const SizedBox(height: 12),
                  _buildInfoItem(
                    icon: Icons.location_on_outlined,
                    iconColor: Colors.orange.shade600,
                    label: '地址',
                    value: supplier.corpAddress!,
                    isMultiLine: true,
                  ),
                ],
                
                // 如果没有任何信息
                if (supplier.contacts?.isEmpty != false &&
                    supplier.phone?.isEmpty != false &&
                    supplier.corpAddress?.isEmpty != false)
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    child: Center(
                      child: Text(
                        '暂无详细信息',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey.shade500,
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  // 招标文件内容（独立Tab）
  Widget _buildBidFilesContent() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(12),
      child: _buildBidFilesCard(),
    );
  }
  
  // 投标文件内容（独立Tab）
  Widget _buildSupplierFilesContent() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(12),
      child: _buildSupplierFilesCard(),
    );
  }
  
  // 招标文件列表卡片
  Widget _buildBidFilesCard() {
    return Obx(() {
      return Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.grey.shade200, width: 1),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.02),
              blurRadius: 4,
              offset: const Offset(0, 1),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题
            Row(
              children: [
                Icon(Icons.description_outlined, color: Colors.blue.shade600, size: 18),
                const SizedBox(width: 8),
                const Text(
                  '招标文件',
                  style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                if (controller.isLoadingBidFiles.value)
                  SizedBox(
                    width: 14,
                    height: 14,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.blue.shade600),
                    ),
                  )
                else
                  IconButton(
                    icon: Icon(Icons.refresh_rounded, size: 16, color: Colors.grey.shade600),
                    onPressed: controller.refreshBidFiles,
                    tooltip: '刷新招标文件列表',
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                  ),
              ],
            ),
            const SizedBox(height: 16),
            
            // 错误信息
            if (controller.bidFilesErrorMessage.value.isNotEmpty)
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.red.shade50,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.red.shade200),
                ),
                child: Row(
                  children: [
                    Icon(Icons.error_outline, color: Colors.red.shade600, size: 18),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        controller.bidFilesErrorMessage.value,
                        style: TextStyle(color: Colors.red.shade600, fontSize: 13),
                      ),
                    ),
                  ],
                ),
              )
            // 文件列表
            else if (controller.bidFiles.isEmpty && !controller.isLoadingBidFiles.value)
              Container(
                padding: const EdgeInsets.symmetric(vertical: 16),
                child: Center(
                  child: Column(
                    children: [
                      Icon(Icons.insert_drive_file_outlined, size: 32, color: Colors.grey.shade400),
                      const SizedBox(height: 8),
                      Text(
                        '暂无招标文件',
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey.shade500,
                        ),
                      ),
                    ],
                  ),
                ),
              )
            else
              Column(
                children: controller.bidFiles.asMap().entries.map((entry) {
                  final index = entry.key;
                  final file = entry.value;
                  return _buildBidFileItem(file, index);
                }).toList(),
              ),
          ],
        ),
      );
    });
  }
  
  // 供应商文件列表卡片（投标文件）
  Widget _buildSupplierFilesCard() {
    return Obx(() {
      return Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.grey.shade200, width: 1),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.02),
              blurRadius: 4,
              offset: const Offset(0, 1),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题
            Row(
              children: [
                Icon(Icons.attach_file_outlined, color: Colors.purple.shade600, size: 18),
                const SizedBox(width: 8),
                const Text(
                  '投标文件',
                  style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                if (controller.isLoadingSupplierFiles.value)
                  SizedBox(
                    width: 14,
                    height: 14,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.purple.shade600),
                    ),
                  )
                else
                  IconButton(
                    icon: Icon(Icons.refresh_rounded, size: 16, color: Colors.grey.shade600),
                    onPressed: controller.refreshSupplierFiles,
                    tooltip: '刷新文件列表',
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                  ),
              ],
            ),
            const SizedBox(height: 16),
            
            // 错误信息
            if (controller.supplierFilesErrorMessage.value.isNotEmpty)
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.red.shade50,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.red.shade200),
                ),
                child: Row(
                  children: [
                    Icon(Icons.error_outline, color: Colors.red.shade600, size: 18),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        controller.supplierFilesErrorMessage.value,
                        style: TextStyle(color: Colors.red.shade600, fontSize: 13),
                      ),
                    ),
                  ],
                ),
              )
            // 文件列表
            else if (controller.supplierFiles.isEmpty && !controller.isLoadingSupplierFiles.value)
              Container(
                padding: const EdgeInsets.symmetric(vertical: 16),
                child: Center(
                  child: Column(
                    children: [
                      Icon(Icons.insert_drive_file_outlined, size: 32, color: Colors.grey.shade400),
                      const SizedBox(height: 8),
                      Text(
                        '暂无投标文件',
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey.shade500,
                        ),
                      ),
                    ],
                  ),
                ),
              )
            else
              Column(
                children: controller.supplierFiles.asMap().entries.map((entry) {
                  final index = entry.key;
                  final file = entry.value;
                  return _buildFileItem(file, index, Colors.purple);
                }).toList(),
              ),
          ],
        ),
      );
    });
  }
  
  // 招标文件项（蓝色主题）
  Widget _buildBidFileItem(SupplierFileModel file, int index) {
    return _buildFileItem(file, index, Colors.blue, controller.bidFiles.length);
  }
  
  // 文件项（通用，支持自定义颜色）
  Widget _buildFileItem(SupplierFileModel file, int index, MaterialColor themeColor, [int? totalCount]) {
    final fileCount = totalCount ?? controller.supplierFiles.length;
    
    return Container(
      margin: EdgeInsets.only(bottom: index < fileCount - 1 ? 8 : 0),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: themeColor.shade50,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: themeColor.shade100, width: 1),
      ),
      child: Row(
        children: [
          // 文件图标
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: themeColor.shade100,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(
              _getFileIcon(file.fileExt),
              size: 20,
              color: themeColor.shade700,
            ),
          ),
          const SizedBox(width: 12),
          
          // 文件信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  file.fileName ?? '未知文件',
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: Colors.grey.shade800,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                Row(
                  children: [
                    Icon(Icons.storage_outlined, size: 12, color: Colors.grey.shade500),
                    const SizedBox(width: 4),
                    Text(
                      file.fileSizeReadable,
                      style: TextStyle(
                        fontSize: 11,
                        color: Colors.grey.shade600,
                      ),
                    ),
                    // 优先显示uploadTime，如果没有则显示createTime
                    if ((file.uploadTime?.isNotEmpty == true) || 
                        (file.createTime?.isNotEmpty == true)) ...[
                      const SizedBox(width: 12),
                      Icon(Icons.access_time, size: 12, color: Colors.grey.shade500),
                      const SizedBox(width: 4),
                      Flexible(
                        child: Text(
                          file.uploadTime?.isNotEmpty == true 
                              ? file.uploadTime! 
                              : file.createTime!,
                          style: TextStyle(
                            fontSize: 11,
                            color: Colors.grey.shade600,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ],
                ),
              ],
            ),
          ),
          
          // 下载按钮
          Obx(() {
            final fileId = file.id;
            final isDownloadingFile = fileId != null && (controller.isDownloading[fileId] == true);
            final progress = fileId != null ? (controller.downloadProgress[fileId] ?? 0.0) : 0.0;
            
            if (isDownloadingFile && progress > 0 && progress < 1) {
              // 显示下载进度
              return SizedBox(
                width: 32,
                height: 32,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    SizedBox(
                      width: 24,
                      height: 24,
                      child: CircularProgressIndicator(
                        value: progress,
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(themeColor.shade600),
                        backgroundColor: themeColor.shade100,
                      ),
                    ),
                    Text(
                      '${(progress * 100).toInt()}',
                      style: TextStyle(
                        fontSize: 8,
                        fontWeight: FontWeight.bold,
                        color: themeColor.shade700,
                      ),
                    ),
                  ],
                ),
              );
            }
            
            // 正常下载按钮
            return IconButton(
              icon: Icon(
                Icons.download_outlined, 
                size: 18, 
                color: isDownloadingFile ? Colors.grey.shade400 : themeColor.shade600,
              ),
              onPressed: isDownloadingFile ? null : () => controller.downloadSupplierFile(file),
              padding: EdgeInsets.zero,
              constraints: const BoxConstraints(),
              tooltip: isDownloadingFile ? '下载中...' : '下载文件',
            );
          }),
        ],
      ),
    );
  }
  
  // 根据文件扩展名获取图标
  IconData _getFileIcon(String? ext) {
    if (ext == null || ext.isEmpty) return Icons.insert_drive_file_outlined;
    
    final extension = ext.toLowerCase().replaceAll('.', '');
    switch (extension) {
      case 'pdf':
        return Icons.picture_as_pdf_outlined;
      case 'doc':
      case 'docx':
        return Icons.description_outlined;
      case 'xls':
      case 'xlsx':
        return Icons.table_chart_outlined;
      case 'ppt':
      case 'pptx':
        return Icons.slideshow_outlined;
      case 'zip':
      case 'rar':
      case '7z':
        return Icons.folder_zip_outlined;
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
      case 'bmp':
        return Icons.image_outlined;
      case 'txt':
        return Icons.text_snippet_outlined;
      default:
        return Icons.insert_drive_file_outlined;
    }
  }
  
  // 签名板区域（第二步）
  Widget _buildSignatureSection() {
    return Obx(() {
      return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Card(
          elevation: 1,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(Icons.draw, color: Colors.blue.shade600, size: 20),
                    const SizedBox(width: 8),
                    const Text(
                      '专家签名',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.red.shade100,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        '必填',
                        style: TextStyle(
                          fontSize: 10,
                          fontWeight: FontWeight.bold,
                          color: Colors.red.shade700,
                        ),
                      ),
                    ),
                    const Spacer(),
                    if (controller.hasSignature.value)
                      TextButton.icon(
                        onPressed: controller.onClearSignature,
                        icon: const Icon(Icons.clear, size: 16),
                        label: const Text('清除'),
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.red.shade600,
                          padding: const EdgeInsets.symmetric(horizontal: 8),
                        ),
                      ),
                  ],
                ),
                const SizedBox(height: 12),
                
                // 手写签名板
                Container(
                  width: double.infinity,
                  height: 200,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: Colors.grey.shade300, width: 2),
                    color: Colors.white,
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(6),
                    child: Signature(
                      controller: controller.signatureController,
                      backgroundColor: Colors.white,
                    ),
                  ),
                ),
                const SizedBox(height: 8),
                
                // 签名提示
                Row(
                  children: [
                    Icon(Icons.info_outline, size: 14, color: Colors.grey.shade600),
                    const SizedBox(width: 4),
                    Text(
                      '请在上方白色区域内手写签名',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey.shade600,
                      ),
                    ),
                  ],
                ),
                
                // 错误信息
                if (controller.uploadErrorMessage.value.isNotEmpty) ...[
                  const SizedBox(height: 12),
                  Container(
                    padding: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      color: Colors.red.shade50,
                      borderRadius: BorderRadius.circular(6),
                      border: Border.all(color: Colors.red.shade200),
                    ),
                    child: Row(
                      children: [
                        Icon(Icons.error_outline, color: Colors.red.shade600, size: 16),
                        const SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            controller.uploadErrorMessage.value,
                            style: TextStyle(
                              color: Colors.red.shade600,
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ],
            ),
          ),
        ),
      );
    });
  }

  // 评分规则部分（紧凑版）
  Widget _buildScoreRulesSection(String scoreRuleJson) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 4),
      child: _buildScoreRulesList(scoreRuleJson),
    );
  }
  
  // 构建可展开/收起的评分标准
  Widget _buildExpandableStandard({
    required String key,
    required String standard,
  }) {
    final isExpanded = _expandedStandards[key] ?? false;
    
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(6),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4),
        border: Border.all(color: Colors.grey.shade300),
      ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
            crossAxisAlignment: CrossAxisAlignment.start,
              children: [
              // 评分标准标签
              Text(
                '评分标准：',
                  style: TextStyle(
                  fontSize: 11,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey.shade700,
                ),
              ),
              
              // 标准内容
              Expanded(
                child: Text(
                  standard,
                  style: const TextStyle(
                    fontSize: 11,
                    height: 1.3,
                  ),
                  maxLines: isExpanded ? null : 1,
                  overflow: isExpanded ? TextOverflow.visible : TextOverflow.ellipsis,
                ),
              ),
              
              // 展开/收起按钮（只在内容超过一行时显示）
              if (_needsExpandButton(standard))
                GestureDetector(
                  onTap: () {
                    setState(() {
                      _expandedStandards[key] = !isExpanded;
                    });
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    margin: const EdgeInsets.only(left: 4),
                    decoration: BoxDecoration(
                      color: Colors.blue.shade50,
                      borderRadius: BorderRadius.circular(4),
                      border: Border.all(color: Colors.blue.shade200, width: 0.5),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          isExpanded ? '收起' : '展开',
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.blue.shade700,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        const SizedBox(width: 2),
                        Icon(
                          isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                          size: 14,
                          color: Colors.blue.shade700,
                ),
              ],
            ),
                  ),
                ),
          ],
        ),
        ],
      ),
    );
  }
  
  // 判断文本是否需要展开按钮（简单判断：长度超过50个字符）
  bool _needsExpandButton(String text) {
    // 粗略估计：超过40个字符可能需要多行显示
    return text.length > 40;
  }

  // 评分规则列表
  Widget _buildScoreRulesList(String scoreRuleJson) {
    try {
      final List<dynamic> scoreRules = jsonDecode(scoreRuleJson);
      
      return Column(
        children: scoreRules.map<Widget>((rule) {
          final Map<String, dynamic> ruleMap = rule as Map<String, dynamic>;
          final String type = ruleMap['type'] ?? '';
          final String criteria = ruleMap['criteria'] ?? '';
          final String content = ruleMap['content'] ?? '';
          final String standard = ruleMap['standard'] ?? '';
          final String score = ruleMap['score'] ?? '';
          final List<dynamic> subItems = ruleMap['subItems'] ?? [];
          
          // 总分行（紧凑版）
          if (type == 'total') {
            return Container(
              margin: const EdgeInsets.only(top: 6),
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
              decoration: BoxDecoration(
                color: Colors.green.shade50,
                borderRadius: BorderRadius.circular(6),
                border: Border.all(color: Colors.green.shade200),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      '总分',
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.bold,
                        color: Colors.green.shade700,
                      ),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.green.shade100,
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      '$score分',
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                        color: Colors.green.shade700,
                      ),
                    ),
                  ),
                ],
              ),
            );
          }
          
          return Container(
            margin: const EdgeInsets.only(bottom: 8),
            decoration: BoxDecoration(
              color: Colors.grey.shade50,
              borderRadius: BorderRadius.circular(6),
              border: Border.all(color: Colors.grey.shade200),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 评审项目标题（如：价格部分、商务部分、技术部分）- 紧凑版
                if (criteria.isNotEmpty)
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                    decoration: BoxDecoration(
                      color: Colors.blue.shade100,
                      borderRadius: const BorderRadius.vertical(top: Radius.circular(5)),
                    ),
                    child: Text(
                      criteria,
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.bold,
                        color: Colors.blue.shade800,
                      ),
                    ),
                  ),
                
                // 评审内容（包含评分标准和分值）- 紧凑版
                if (content.isNotEmpty) ...[
                  Container(
                    padding: const EdgeInsets.all(8),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 评审内容标题
                        Text(
                          content,
                          style: const TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        
                        // 评分标准（同一行显示，支持展开/收起）
                        if (standard.isNotEmpty) ...[
                          const SizedBox(height: 6),
                          _buildExpandableStandard(
                            key: 'main_${content}_${criteria}',
                            standard: standard,
                          ),
                        ],
                        
                        // 分值输入区域（紧凑版）
                        if (score.isNotEmpty) ...[
                          const SizedBox(height: 6),
                          Row(
                            children: [
                              Expanded(
                                child: Container(
                                  height: 38,
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(4),
                                    border: Border.all(color: Colors.orange.shade300, width: 1.5),
                                  ),
                                  child: Builder(
                                    builder: (context) {
                                      // 为每个评分项创建唯一的 key
                                      final scoreKey = 'score_${content}_${criteria}';
                                      
                                      // 如果还没有创建 controller，则创建一个
                                      if (!controller.scoreControllers.containsKey(scoreKey)) {
                                        controller.scoreControllers[scoreKey] = TextEditingController();
                                      }
                                      
                                      return TextField(
                                        controller: controller.scoreControllers[scoreKey],
                                        keyboardType: TextInputType.numberWithOptions(decimal: true),
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                          fontSize: 14,
                                          fontWeight: FontWeight.bold,
                                          color: Colors.orange.shade700,
                                        ),
                                        decoration: InputDecoration(
                                          hintText: '请输入分数',
                                          hintStyle: TextStyle(
                                            fontSize: 12,
                                            color: Colors.grey.shade400,
                                          ),
                                          border: InputBorder.none,
                                          contentPadding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                                        ),
                                      );
                                    },
                                  ),
                                ),
                              ),
                              const SizedBox(width: 6),
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                                decoration: BoxDecoration(
                                  color: Colors.orange.shade50,
                                  borderRadius: BorderRadius.circular(4),
                                  border: Border.all(color: Colors.orange.shade200),
                                ),
                                child: Text(
                                  '$score分',
                                  style: TextStyle(
                                    fontSize: 11,
                                    fontWeight: FontWeight.bold,
                                    color: Colors.orange.shade700,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ],
                    ),
                  ),
                ],
                
                // 子项评审内容（紧凑版）
                if (subItems.isNotEmpty) ...[
                  const Padding(
                    padding: EdgeInsets.symmetric(horizontal: 8),
                    child: Divider(height: 1),
                  ),
                  ...subItems.asMap().entries.map<Widget>((entry) {
                    final index = entry.key;
                    final subItem = entry.value;
                    final Map<String, dynamic> subMap = subItem as Map<String, dynamic>;
                    final String subContent = subMap['content'] ?? '';
                    final String subStandard = subMap['standard'] ?? '';
                    final String subScore = subMap['score'] ?? '';
                    
                    return Container(
                      padding: const EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        border: Border(
                          top: index > 0 ? BorderSide(color: Colors.grey.shade300) : BorderSide.none,
                        ),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 子项标题
                          if (subContent.isNotEmpty) ...[
                            Text(
                              subContent,
                              style: const TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                          
                          // 子项评分标准（同一行显示，支持展开/收起）
                          if (subStandard.isNotEmpty) ...[
                            const SizedBox(height: 6),
                            _buildExpandableStandard(
                              key: 'sub_${content}_${subContent}_$index',
                              standard: subStandard,
                            ),
                          ],
                          
                          // 子项分值输入区域（紧凑版）
                          if (subScore.isNotEmpty) ...[
                            const SizedBox(height: 6),
                            Row(
                              children: [
                                Expanded(
                                  child: Container(
                                    height: 38,
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(4),
                                      border: Border.all(color: Colors.orange.shade300, width: 1.5),
                                    ),
                                    child: Builder(
                                      builder: (context) {
                                        // 为每个子项评分创建唯一的 key
                                        final subScoreKey = 'sub_score_${content}_${subContent}_$index';
                                        
                                        // 如果还没有创建 controller，则创建一个
                                        if (!controller.scoreControllers.containsKey(subScoreKey)) {
                                          controller.scoreControllers[subScoreKey] = TextEditingController();
                                        }
                                        
                                        return TextField(
                                          controller: controller.scoreControllers[subScoreKey],
                                          keyboardType: TextInputType.numberWithOptions(decimal: true),
                                          textAlign: TextAlign.center,
                                          style: TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.bold,
                                            color: Colors.orange.shade700,
                                          ),
                                          decoration: InputDecoration(
                                            hintText: '请输入分数',
                                            hintStyle: TextStyle(
                                              fontSize: 12,
                                              color: Colors.grey.shade400,
                                            ),
                                            border: InputBorder.none,
                                            contentPadding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                                          ),
                                        );
                                      },
                                    ),
                                  ),
                                ),
                                const SizedBox(width: 6),
                                Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                                  decoration: BoxDecoration(
                                    color: Colors.orange.shade50,
                                    borderRadius: BorderRadius.circular(4),
                                    border: Border.all(color: Colors.orange.shade200),
                                  ),
                                  child: Text(
                                    '$subScore分',
                                    style: TextStyle(
                                      fontSize: 11,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.orange.shade700,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ],
                      ),
                    );
                  }).toList(),
                ],
              ],
            ),
          );
        }).toList(),
      );
    } catch (e) {
      return Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.orange.shade50,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Colors.orange.shade200),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(Icons.warning, color: Colors.orange.shade600, size: 20),
                const SizedBox(width: 8),
                Text(
                  '评分规则格式解析异常',
                  style: TextStyle(
                    fontWeight: FontWeight.w500,
                    color: Colors.orange.shade700,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              '原始数据：\n$scoreRuleJson',
              style: TextStyle(
                fontSize: 12,
                color: Colors.orange.shade600,
                fontFamily: 'monospace',
              ),
            ),
          ],
        ),
      );
    }
  }

  // 资格评审规则部分（紧凑版）
  Widget _buildReviewRulesSection(String reviewRuleHtml) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 4),
      child: _buildReviewRulesTable(reviewRuleHtml),
    );
  }

  // 资格评审规则表格
  Widget _buildReviewRulesTable(String reviewRuleHtml) {
    // 简单解析HTML表格内容
    final List<Map<String, String>> tableData = _parseHtmlTable(reviewRuleHtml);
    
    if (tableData.isEmpty) {
      return Container(
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: Colors.grey.shade100,
          borderRadius: BorderRadius.circular(6),
        ),
        child: Column(
          children: [
            Text(
              '原始HTML内容：',
              style: TextStyle(
                fontWeight: FontWeight.w500,
                color: Colors.grey.shade700,
                fontSize: 11,
              ),
            ),
            const SizedBox(height: 6),
            Text(
              reviewRuleHtml,
              style: TextStyle(
                fontSize: 10,
                color: Colors.grey.shade600,
                fontFamily: 'monospace',
              ),
            ),
          ],
        ),
      );
    }
    
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey.shade300),
        borderRadius: BorderRadius.circular(6),
      ),
      child: Column(
        children: [
          // 表头（紧凑版）
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
            decoration: BoxDecoration(
              color: Colors.grey.shade100,
              borderRadius: const BorderRadius.vertical(top: Radius.circular(5)),
            ),
            child: const Row(
              children: [
                SizedBox(
                  width: 35,
                  child: Text(
                    '序号',
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
                  ),
                ),
                Expanded(
                  flex: 3,
                  child: Text(
                    '材料名称',
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: Text(
                    '备注',
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
                  ),
                ),
              ],
            ),
          ),
          
          // 表格内容（紧凑版）
          ...tableData.asMap().entries.map((entry) {
            final index = entry.key;
            final data = entry.value;
            
            return Container(
              decoration: BoxDecoration(
                border: Border(
                  top: index > 0 ? BorderSide(color: Colors.grey.shade300) : BorderSide.none,
                ),
              ),
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(
                      width: 35,
                      child: Text(
                        data['序号'] ?? '${index + 1}',
                        style: const TextStyle(fontSize: 11),
                      ),
                    ),
                    Expanded(
                      flex: 3,
                      child: Text(
                        data['材料名称'] ?? '',
                        style: const TextStyle(fontSize: 11),
                      ),
                    ),
                    Expanded(
                      flex: 2,
                      child: Text(
                        data['备注'] ?? '',
                        style: TextStyle(fontSize: 11, color: Colors.grey.shade600),
                      ),
                    ),
                  ],
                ),
              ),
            );
          }).toList(),
        ],
      ),
    );
  }

  // 简单解析HTML表格
  List<Map<String, String>> _parseHtmlTable(String html) {
    final List<Map<String, String>> result = [];
    
    try {
      // 使用正则表达式简单解析HTML表格行
      final RegExp trRegex = RegExp(r'<tr[^>]*>(.*?)</tr>', dotAll: true);
      final RegExp tdRegex = RegExp(r'<td[^>]*>(.*?)</td>', dotAll: true);
      
      final trMatches = trRegex.allMatches(html);
      
      for (final trMatch in trMatches) {
        final trContent = trMatch.group(1) ?? '';
        final tdMatches = tdRegex.allMatches(trContent);
        
        if (tdMatches.length >= 2) {
          final List<String> cells = tdMatches
              .map((match) => (match.group(1) ?? '').replaceAll(RegExp(r'<[^>]*>'), '').trim())
              .toList();
          
          if (cells.length >= 2 && cells[1].isNotEmpty) {
            result.add({
              '序号': cells.length > 0 ? cells[0] : '',
              '材料名称': cells.length > 1 ? cells[1] : '',
              '备注': cells.length > 2 ? cells[2] : '',
            });
          }
        }
      }
    } catch (e) {
      debugPrint('解析HTML表格失败: $e');
    }
    
    return result;
  }

  // 构建评标专家列表
  Widget _buildProjectExperts() {
    return Obx(() {
      return Card(
        elevation: 1,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.people, size: 16, color: Colors.blue.shade600),
                  const SizedBox(width: 6),
                  Text(
                    '评标专家列表',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue.shade700,
                    ),
                  ),
                  const Spacer(),
                  if (controller.isLoadingExperts.value)
                    SizedBox(
                      width: 14,
                      height: 14,
                      child: CircularProgressIndicator(strokeWidth: 2, color: Colors.blue.shade600),
                    )
                  else
                    IconButton(
                      icon: Icon(Icons.refresh, size: 16, color: Colors.grey.shade600),
                      onPressed: controller.refreshProjectExperts,
                      tooltip: '刷新专家列表',
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                    ),
                ],
              ),
              const SizedBox(height: 8),
              
              if (controller.expertErrorMessage.value.isNotEmpty)
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.red.shade50,
                    borderRadius: BorderRadius.circular(6),
                    border: Border.all(color: Colors.red.shade200),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.error_outline, color: Colors.red.shade600, size: 16),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          controller.expertErrorMessage.value,
                          style: TextStyle(color: Colors.red.shade600, fontSize: 12),
                        ),
                      ),
                      TextButton(
                        onPressed: controller.refreshProjectExperts,
                        style: TextButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          minimumSize: Size.zero,
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        ),
                        child: const Text('重试', style: TextStyle(fontSize: 12)),
                      ),
                    ],
                  ),
                )
              else if (controller.projectExperts.isEmpty && !controller.isLoadingExperts.value)
                Container(
                  padding: const EdgeInsets.all(10),
                  child: Row(
                    children: [
                      Icon(Icons.info_outline, color: Colors.grey.shade600, size: 16),
                      const SizedBox(width: 8),
                      Text(
                        '暂无评标专家信息',
                        style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
                      ),
                    ],
                  ),
                )
              else
                Builder(
                  builder: (context) {
                    // 将当前登录的专家排在第一位
                    final experts = controller.projectExperts.toList();
                    final currentExpertId = controller.currentExpertId;
                    
                    // 找到当前专家的索引
                    final currentExpertIndex = experts.indexWhere(
                      (expert) => expert.expertId == currentExpertId,
                    );
                    
                    // 如果找到当前专家且不在第一位，则移到第一位
                    if (currentExpertIndex > 0) {
                      final currentExpert = experts.removeAt(currentExpertIndex);
                      experts.insert(0, currentExpert);
                    }
                    
                    return ListView.separated(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: experts.length,
                      separatorBuilder: (context, index) => Divider(height: 12, color: Colors.grey.shade200),
                      itemBuilder: (context, index) {
                        final expert = experts[index];
                        return _buildExpertItem(expert);
                      },
                    );
                  },
                ),
            ],
          ),
        ),
      );
    });
  }

  // 专家项目
  Widget _buildExpertItem(ProjectExpert expert) {
    final isCurrentExpert = expert.expertId == controller.currentExpertId;
    
    return Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: isCurrentExpert ? Colors.blue.shade50 : Colors.grey.shade50,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: isCurrentExpert ? Colors.blue.shade300 : Colors.grey.shade200,
          width: isCurrentExpert ? 2 : 1,
        ),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 专家头像
          CircleAvatar(
            radius: 16,
            backgroundColor: isCurrentExpert ? Colors.blue.shade600 : Colors.blue.shade200,
            child: Text(
              expert.expertName?.isNotEmpty == true 
                  ? expert.expertName!.substring(0, 1).toUpperCase()
                  : '?',
              style: TextStyle(
                color: isCurrentExpert ? Colors.white : Colors.blue.shade800,
                fontWeight: FontWeight.bold,
                fontSize: 14,
              ),
            ),
          ),
          const SizedBox(width: 8),
          
          // 专家信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Flexible(
                      child: Text(
                        expert.expertName ?? '未知专家',
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: isCurrentExpert ? Colors.blue.shade900 : Colors.black87,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    if (isCurrentExpert) ...[
                      const SizedBox(width: 4),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
                        decoration: BoxDecoration(
                          color: Colors.blue.shade600,
                          borderRadius: BorderRadius.circular(3),
                        ),
                        child: const Text(
                          '我',
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ],
                  ],
                ),
                const SizedBox(height: 2),
                if (expert.corpName?.isNotEmpty == true && expert.corpName != 'null')
                  Text(
                    expert.corpName!,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey.shade600,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                const SizedBox(height: 3),
                if (expert.officialCapacity?.isNotEmpty == true && expert.officialCapacity != 'null')
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.orange.shade100,
                      borderRadius: BorderRadius.circular(3),
                    ),
                    child: Text(
                      expert.officialCapacity!,
                      style: TextStyle(
                        fontSize: 10,
                        color: Colors.orange.shade800,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建按钮式Tab切换器
  Widget _buildTabSwitcher() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      padding: const EdgeInsets.all(3),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade200, width: 1),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 6,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: _buildTabButton(
              index: 0,
              icon: Icons.assignment_outlined,
              label: '项目详情',
            ),
          ),
          const SizedBox(width: 3),
          Expanded(
            child: _buildTabButton(
              index: 1,
              icon: Icons.business_outlined,
              label: '供应商',
            ),
          ),
        ],
      ),
    );
  }

  // 构建单个Tab按钮
  Widget _buildTabButton({
    required int index,
    required IconData icon,
    required String label,
  }) {
    final isSelected = _selectedIndex == index;
    
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedIndex = index;
        });
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.symmetric(vertical: 10),
        decoration: BoxDecoration(
          color: isSelected ? Colors.blue.shade600 : Colors.transparent,
          borderRadius: BorderRadius.circular(9),
          boxShadow: isSelected
              ? [
                  BoxShadow(
                    color: Colors.blue.withOpacity(0.25),
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  ),
                ]
              : null,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              icon,
              size: 16,
              color: isSelected ? Colors.white : Colors.grey.shade600,
            ),
            const SizedBox(width: 4),
            Text(
              label,
              style: TextStyle(
                fontSize: 13,
                fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
                color: isSelected ? Colors.white : Colors.grey.shade600,
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CaigouAssessmentDetialController>(
      init: CaigouAssessmentDetialController(),
      id: "caigou_assessment_detial",
      builder: (_) {
        return Scaffold(
          backgroundColor: Colors.grey.shade50,
          appBar: AppBar(
            elevation: 0,
            backgroundColor: Colors.white,
            surfaceTintColor: Colors.white,
            toolbarHeight: 50,
            leading: IconButton(
              icon: Icon(
                Icons.arrow_back_ios_new_rounded,
                color: Colors.grey[800],
                size: 18,
              ),
              onPressed: () => Get.back(),
              padding: const EdgeInsets.all(8),
            ),
            title: Text(
              "项目采购评审详情",
              style: TextStyle(
                color: Colors.grey[900],
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            bottom: PreferredSize(
              preferredSize: const Size.fromHeight(1),
              child: Container(
                height: 1,
                color: Colors.grey.shade100,
              ),
            ),
          ),
          body: SafeArea(
            child: Stack(
              children: [
                Column(
                  children: [
                    // 按钮式Tab切换器
                    _buildTabSwitcher(),
                    
                    // 内容区域
                    Expanded(
                      child: IndexedStack(
                        index: _selectedIndex,
                        children: [
                          _buildProjectDetailView(),
                          _buildSuppliersView(),
                        ],
                      ),
                    ),
                  ],
                ),
                _buildSupplierBidBottomSheet(),
              ],
            ),
          ),
        );
      },
    );
  }
}
